<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
//随机生成器
use think\facade\Config;

if(!function_exists('get_rand')) {
    function get_rand()
    {
        $now = $_SERVER['REQUEST_TIME'];//当前系统时间，比time()多5秒
        return rand() . $now;
    }
}

if(!function_exists('wapAjaxReturn')) {
    /**
     * Kyle
     *  wapAjaxReturn
     * @param int $error_code 错误代码，0表是成功
     * @param string $msg 返回信息
     * @param string $data 返回数据
     * @param string $url 返回url
     * @param string $source 返回资源路径
     */
    function wapAjaxReturn($error_code = '0', $msg = '', $data = '', $url = '', $source = '')
    {
        $re = array();
        $re['error_code'] = $error_code;
        $re['msg'] = $msg;
        $re['data'] = $data !== '' ? $data : (object)null;
        $re['url'] = $url;
        $re['source'] = $source;
        exit(json_encode($re));
    }
}
if(!function_exists('crossdomain')) {
    function crossdomain()
    {
        //允许多个域名访问
        $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
        // dump($origin);exit;
        if (!empty($origin)) {
            if (strpos($origin, Config::get('params.crossDomain'))) {
                header('Access-Control-Allow-Origin:' . $origin);
            }
        }
        //允许跨域
        header("Access-Control-Allow-Credentials:true");
        header('Access-Control-Allow-Methods: GET, POST');
        header('Access-Control-Max-Age: 3628800');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
        header('Content-Type:application/json;charset=utf-8');
    }
}

if(!function_exists('validate_time_stamp')){
    /**
     * Desc: sign 校验，限制 (限制接口超时60秒)
     * User: Kyle
     * @param $timestamp
     * @return array
     */
    function validate_time_stamp($timestamp = ''){
        $re = [
            'error_code'=> 0,
            'msg'=>'',
        ];;
        if(!$timestamp || !is_numeric($timestamp)){
            $re = [
                'error_code'=> 81001,
                'msg'=>'参数错误',
            ];
        }

        elseif($timestamp + 60 <= time()){
            $re = [
                'error_code'=> 81002,
                'msg'=>'请求超时',
            ];
        }

        return $re;

    }
}


if(!function_exists('getApiSignature')){
    /**
     * Desc:认证签名方法
     * User: Kyle
     * @param $params
     * @param string $secret
     * @return string
     */
    function getApiSignature($params, $secret=''){
        $str = '';  //待签名字符串
        //先将参数以其参数名的字典序升序进行排序
        ksort($params);
        //遍历排序后的参数数组中的每一个key/value对
        foreach ($params as $k => $v) {
            //为key/value对生成一个key=value格式的字符串，并拼接到待签名字符串后面
            $str .= "$k=$v";
        }
        //将签名密钥拼接到签名字符串最后面
        $str .= $secret;

        //通过md5算法为签名字符串生成一个md5签名，该签名就是我们要追加的sign参数值
        //wapAjaxReturn($params,$str,md5($str));

        return md5($str);
    }
}


if(!function_exists('curl_file_get_contents')){
    /**
     * curl 请求数据
     * curl_file_get_contents($url, $postFields = null, $timeout = 100)
     * */
    function curl_file_get_contents($url, $postFields = null, $timeout = 100,$cookie='')
    {
        set_time_limit(0);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; rv:26.0) Gecko/20100101 Firefox/26.0');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        if($cookie){
            curl_setopt($ch,CURLOPT_COOKIE,$cookie);
        }
        if ($postFields) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        }

        $r = curl_exec($ch);
        curl_close($ch);

        return $r;
    }
}

if(!function_exists('aL')) {
// 判断数组是几维数组
    function aL($data, &$al = array(0), $level = 0)
    {
        if (is_array($data)) {
            $level++;
            $al[] = $level;
            foreach ($data as $v) {
                aL($v, $al, $level);
            }
        }
        return max($al);
    }
}

if(!function_exists('curl_file_get_contents')){
    /**
     * curl 请求数据
     * curl_file_get_contents($url, $postFields = null, $timeout = 100)
     * */
    function curl_file_get_contents($url, $postFields = null, $timeout = 100,$cookie='')
    {
        set_time_limit(0);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; rv:26.0) Gecko/20100101 Firefox/26.0');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        if($cookie){
            curl_setopt($ch,CURLOPT_COOKIE,$cookie);
        }
        if ($postFields) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        }

        $r = curl_exec($ch);
        curl_close($ch);

        return $r;
    }

}

if(!function_exists('getThumbImg')){
    /**
     * @param $img
     * @param string $imgSize
     * @return string
     * 获取图片全路径及生成缩略图
     */
    function getThumbImg($img,$imgSize=''){
        if($img){
            if($imgSize){
                $fileNameStr = explode(".",$img);
                $imageExt = end($fileNameStr); unset($fileNameStr[count($fileNameStr)-1]);
                $img = implode(".",$fileNameStr) . '@' . $imgSize . '.' . $imageExt;
            }

            return Config::get('params.php_server') . $img;
        }
        return $img;
    }
}

if(!function_exists('getPointLen')){
    //获取字符串小数点位数
    function getPointLen($str){
        $arr = explode(".",$str);
        if(!empty($arr[1])){
            return strlen($arr[1]);
        }
        return 0;
    }
}

if(!function_exists('writeLog')){
    /**
     * log写入
     * @param $log array|obj|string log内容
     * @param string $category 标志
     */
    function writeLog($log,$category= 'app_wirtelog')
    {
        if(is_array($log)){
            $msg = json_encode($log);
        }else if(is_object($log)){
            $msg = print_r($log,true);
        }else{
            $msg = $log;
        }

        $fileName = 'log/'.date('Ymd').'-log.txt';
        if(!file_exists('log')){mkdir('log');}
        file_put_contents($fileName,date('Ymd-His').$category."\r\n",FILE_APPEND);
        file_put_contents($fileName,$msg."\r\n",FILE_APPEND);
        file_put_contents($fileName,"-----------------------------------------------"."\r\n",FILE_APPEND);
    }
}

if(!function_exists('')){
    /**
     * 服务器没代理情况下获取ip方法
     * @return array|false|mixed|string
     */
    function get_client_ip(){
        if (getenv('HTTP_CLIENT_IP')) {
            $ip = getenv('HTTP_CLIENT_IP');
        }else if (getenv('HTTP_X_FORWARDED_FOR_POUND')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR_POUND');
        } else if (getenv('HTTP_X_FORWARDED_FOR')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } else if (getenv('REMOTE_ADDR')) {
            $ip = getenv('REMOTE_ADDR');
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }

        preg_match('/[\\d\\.]{7,15}/',$ip,$onlineIp);
        $realIp = (!empty($onlineIp[0]) ? $onlineIp[0] : '0.0.0.0');
        return $realIp;
    }
}

if(!function_exists('getTtSignature')){
    /**
     * 头条支付秘钥生成
     * @param $params
     * @param string $secret
     * @return string
     */
    function getTtSignature($params, $secret=''){
        $str = "";  //待签名字符串
        //先将参数以其参数名的字典序升序进行排序
        ksort($params);

        //遍历排序后的参数数组中的每一个key/value对
        foreach ($params as $k => $v) {
            if (!$v || in_array($k,["risk_info", "sign"])) {
                continue;
            }
            if(strlen($str) > 0){
                $str .= "&";
            }
            //为key/value对生成一个key=value格式的字符串，并拼接到待签名字符串后面
            $str .= $k."=".$v;
        }
        //将签名密钥拼接到签名字符串最后面
        $str .= $secret;
        //通过md5算法为签名字符串生成一个md5签名，该签名就是我们要追加的sign参数值
        return md5($str);
    }
}

/**
 * @param $id 要进行校验的id
 * @param $ids 被校验的id字符串，以逗号隔开
 * return 存在返回true 不存在返回false
 */
function IN_ARRAY_ID($id=0,$ids=""){
    if(!empty($ids) || !is_array($ids)){
        $ids = explode(",",$ids);
        if(in_array($id,$ids)){
            RETURN true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

function GetRandStr($len)
{
    $chars = array(
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
        "3", "4", "5", "6", "7", "8", "9"
    );
    $charsLen = count($chars) - 1;
    shuffle($chars);
    $output = "";
    for ($i=0; $i<$len; $i++)
    {
        $output .= $chars[mt_rand(0, $charsLen)];
    }
    return $output;
}


function httpByPost($url, $data = NULL, $json = false)

{

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $url);

    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

    if (!empty($data)) {

        if($json && is_array($data)){

            $data = json_encode( $data );

        }

        curl_setopt($curl, CURLOPT_POST, 1);

        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

        if($json){ //发送JSON数据

            curl_setopt($curl, CURLOPT_HEADER, 0);

            curl_setopt($curl, CURLOPT_HTTPHEADER,
                array(
                    'Content-Type: application/json; charset=utf-8',
                    'Content-Length:' . strlen($data)));
        }
    }

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $res = curl_exec($curl);

    $errorno = curl_errno($curl);


    if ($errorno) {

        return array('errorno' => false, 'errmsg' => $errorno);

    }

    curl_close($curl);

    return json_decode($res, true);

}